#include <func.h>

// 服务端
int main(void)
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if(fd == -1)
        error(1, errno, "socket");

    struct sockaddr_in addr;
    addr.sin_port = htons(atoi("8080"));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    int reuse = 1;
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    if(bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1)
        error(1, errno, "bind");

    if(listen(fd, 10) == -1)
        error(1, errno, "listen");

    int people = 0;
    int c_fd[2];
    fd_set next_set;
    FD_ZERO(&next_set);
    FD_SET(fd, &next_set);
    while(1)
    {
        fd_set set = next_set;

        if(select(20, &set, NULL, NULL, NULL) == -1)
            error(1, errno, "select");

        if(FD_ISSET(fd, &set) && people != 2)
        {
            c_fd[people] = accept(fd, NULL ,NULL);
            people++;
            if(people == 2)
            {
                FD_SET(c_fd[0], &next_set);
                FD_SET(c_fd[1], &next_set);
                FD_CLR(fd, &next_set);
            }
        }
        char buf[128] = {0};
        if(FD_ISSET(c_fd[0], &set))
        {
            ssize_t err = recv(c_fd[0], buf, 128, 0);
            // 判断
            if(err == -1)
                error(1, errno, "recv");
            else if(err == 0)
            {
                
                FD_CLR(c_fd[0], &next_set);
                FD_CLR(c_fd[1], &next_set);
                FD_SET(fd, &next_set);
                close(c_fd[0]);
                close(c_fd[1]);
                people = 0;
            }
            else
            {
                if(send(c_fd[1], buf, 128, 0) == -1)
                    error(1, errno, "send");
            }
        }
        if(FD_ISSET(c_fd[1], &set))
        {
            ssize_t err = recv(c_fd[1], buf, 128, 0);
            // 判断
            if(err == -1)
                error(1, errno, "recv");
            else if(err == 0)
            {
                FD_CLR(c_fd[0], &next_set);
                FD_CLR(c_fd[1], &next_set);
                FD_SET(fd, &next_set);
                close(c_fd[0]);
                close(c_fd[1]);
                people = 0;
            }
            else
            {
                if(send(c_fd[0], buf, 128, 0) == -1)
                    error(1, errno, "send");
            }
        }
    }
    return 0;
}